﻿#region Usings
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using BK.BL;
using BK.Entities;
using BK.WebSite.AppCode;
using Lib.ApplicationBlocks.Modules.Web.General;
using Lib.Data.CriteriaRoutine;
using Lib.Data.ORM.Entity;
using Lib.Utils.WebUtils;
using Lib.Utils.WebUtils.UrlTools;
#endregion

namespace BK.WebSite.Controls
{
    public partial class CategoryListControl : BkDataListControl<CategoryEntity, Categories>
    {
        #region Instance Methods
        protected override CategoryEntity[] DoGetEntities()
        {
            List<CategoryEntity> result = new List<CategoryEntity>(base.DoGetEntities());

            if (ParentId.AllKeysHasValue)
            {
                CategoryEntity goToLevelUp = new CategoryEntity
                                                 {
                                                     Name = ".."
                                                 };
                goToLevelUp.Id.Value = GetEntityView().GetParentId(ParentId).Value;
                result.Insert(0, goToLevelUp);
            }

            return result.ToArray();
        }

        protected override bool HandleItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == WebConstants.CommandNames.ENTER_IN)
            {
                UrlBuilder urlBuilder = new UrlBuilder("~" + Request.Url.AbsolutePath);
                string commandArgument = e.CommandArgument.ToString();
                if (!string.IsNullOrEmpty(commandArgument))
                {
                    urlBuilder.Add(new UrlParameter(WebConstants.UrlParams.PARENT_ID, commandArgument), true);
                }

                Response.Redirect(urlBuilder.ToString());

                return true;
            }

            return false;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
        }
        #endregion

        #region Instance Properties
        public override string Key
        {
            get { return "Categories"; }
        }

        public override Criteria RequiredCriteria
        {
            get
            {
                Criteria result = new Criteria("UserId.Value", Clause.Eq, UserProvider.GetCurrentUser().Id.Value);
                result.And("ParentId.Value", Clause.Eq, ParentId.Value);
                return result;
            }
        }

        public IdentifierInt ParentId
        {
            get { return new IdentifierInt(RequestManager.GetNullableInt(WebConstants.UrlParams.PARENT_ID)); }
        }
        #endregion
    }
}